//
//  YJDZFffment.m
//  XOWMSDK
//
//  Created by SKL on 2017/11/8.
//  Copyright © 2017年 SKL. All rights reserved.
//

#import "XOWMPlatform.h"
#import "XOWMZFController.h"
#import "XOWMLoginViewController.h"
#import "XOWMRegisterViewController.h"
#import "XOWMUserViewController.h"
@interface XOWMPlatform()<YJDZFControllerDelegate,YJDLoginViewControllerDelegate,YJDUserViewControllerDelegate>
@property (nonatomic, strong) XOWMLoginViewController *loginVC;
@property (nonatomic, strong) XOWMZFController *zhifuvc;
@property (nonatomic, strong) NSMutableDictionary *receiveDict;
@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, strong) CCMoveTouch *userBtn;
@property (nonatomic, strong) NSMutableData *recevieData;
/*
 code == -1 初始化未开始或者还未完成，
 code == 200 初始化成功
 code == 201 断网
 code == 202 网络抛出异常
 code == 203 验签失败
 code == 204 账号错误/密码错误/应用不存在
 code == 300 循环操作
 */
@property (nonatomic, assign) int statusCode;
/**
 *@pragma
 */
@property (nonatomic, copy) NSString *info;
@end

@implementation XOWMPlatform


static XOWMPlatform *_YJDPlatform;
static dispatch_once_t onceToken;
static XOWMPlatformPara _para;
static XOWMHelperPara _helper;
XOWMPlatformManager platformManager()
{
    XOWMPlatformManager manager =
    {
        _platform,
        _getPara,
        _setPara,
        _destroy,
        _registerPlatform,
        _platformStyle,
        _platformLayout,
        _platformColorType,
        _prepareLogin,
        _prepareRegister,
        _zunbeizhifu,
        _cancelzhifu
    };
    return manager;
}
static XOWMPlatformPara _getPara()
{
    return _para;
}
static void _setPara(XOWMPlatformPara para)
{
    _para = para;
}
static void _destroy(XOWMPlatformPara para)
{
    para.callback = nil;
    _para = para;
}
static XOWMPlatform * _platform()
{
    if (!_YJDPlatform)
    {
        dispatch_once(&onceToken,^{
            _YJDPlatform = [[XOWMPlatform alloc]init];
            _YJDPlatform.userBtn = [CCMoveTouch touch];
            _YJDPlatform.userBtn.hidden = YES;
            _YJDPlatform.userBtn.image = [@"portrait" yjd_image];
            [CCNotice addObs:_YJDPlatform sel:@selector(actionForUserCenter) name:CCNoticeNameMoveTouchClicked obj:nil];
            [[NSNotificationCenter defaultCenter] addObserver:_YJDPlatform selector:@selector(getIP:) name:CCNoticeNameIP object:nil];
        });
    }
    return  _YJDPlatform;
}
static void _registerPlatform(NSString *appID, NSString *serviceHeader, NSString *key)
{
    _YJDPlatform = _platform();
    _para = _getPara();
   
    _helper = helperManager().getPara();
    _helper.appID = appID;
    _helper.serviceHeader = serviceHeader;
    _helper.publicKey = key;
    helperManager().setPara(_helper);
    
    _YJDPlatform.statusCode = -1;
    _YJDPlatform.info = nil;
    
    if (_YJDPlatform.task)
    {
        [_YJDPlatform.task cancel];
        _YJDPlatform.task = nil;
    }
    NSString *ip = [CCIP IP].wanIP?[CCIP IP].wanIP:@"";
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *para = @{@"appid":appID,@"imei":[CCDevice UUID],@"ip":ip,@"terminal":@"1"};
        _YJDPlatform.task = [XOWMHttps post:INIT_API parameters:para delegate:_YJDPlatform];
    });
}
static void _platformStyle(XOWMPlatformStyle style)
{
  _helper.style = style;
    helperManager().setPara(_helper);
}
static void _platformLayout(XOWMPlatformLayout layout)
{
    _helper.layout = layout;
    helperManager().setPara(_helper);
}
static void _platformColorType(XOWMPlatformColor type, UIColor *color)
{
    if (type == XOWMPlatformColorDefault) _helper.color = THEME_COLOR;
    else if (type == XOWMPlatformColorRed) _helper.color = RED_COLOR;
    else if (type == XOWMPlatformColorBlue) _helper.color = BLUE_COLOR;
    else if (type == XOWMPlatformColorOrange) _helper.color = ORANGE_COLOR;
    else if (type == XOWMPlatformColorCustom) _helper.color = color;
    helperManager().setPara(_helper);
}
static void _prepareLogin()
{
    _helper = helperManager().getPara();
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_YJDPlatform.statusCode == 200)
        {
            [CCHud stopHud];
            [_YJDPlatform.loginVC yjd_pop];
        }
        else if (_YJDPlatform.statusCode == 300 || _YJDPlatform.statusCode == -1)
        {
            [CCHud startHud];
            _prepareLogin();
        }
        else if ( _YJDPlatform.statusCode == 201 || _YJDPlatform.statusCode == 202 || _YJDPlatform.statusCode == 203 || _YJDPlatform.statusCode == 204)
        {
            [CCHud stopHud];
            [CCAlert showMessage:[NSString stringWithFormat:@"%d:%@",_YJDPlatform.statusCode,_YJDPlatform.info] hidden:^{
                _registerPlatform(_helper.appID, _helper.serviceHeader, _helper.publicKey);
                _YJDPlatform.statusCode = 300;
                _prepareLogin();
            }];
        }
    });
}
static void _prepareRegister()
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_YJDPlatform.statusCode == 200)
        {
            [CCHud stopHud];
            [[[XOWMRegisterViewController alloc] init] yjd_pop];
        }
        else if (_YJDPlatform.statusCode == 300 || _YJDPlatform.statusCode == -1)        {
            [CCHud startHud];
            _prepareRegister();
        }
        else if ( _YJDPlatform.statusCode == 201 || _YJDPlatform.statusCode == 202 || _YJDPlatform.statusCode == 203 || _YJDPlatform.statusCode == 204)
        {
            [CCHud stopHud];
            [CCAlert showMessage:[NSString stringWithFormat:@"%d:%@",_YJDPlatform.statusCode,_YJDPlatform.info] hidden:^{
                [CCHud startHud];
                _registerPlatform(_helper.appID, _helper.serviceHeader, _helper.publicKey);
                _YJDPlatform.statusCode = 300;
                _prepareRegister();
            }];
        }
        
    });
}
static void _zunbeizhifu(XOWMProductPara product)
{
    _helper = helperManager().getPara();
    if ([_helper.accountID length] < 1 || [_helper.token length] < 1)
    {
        [CCAlert showMessage:@"检测到您未登录，请先登录" title:@"错误" enter:^{
            _prepareLogin();
        }];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [_YJDPlatform.zhifuvc yjd_zunbeizf:product];
        });
    }
}
static void _cancelzhifu()
{
    
}
- (XOWMLoginViewController *)loginVC
{
    if (!_loginVC)
    {
        _loginVC = [[XOWMLoginViewController alloc]init];
        _loginVC.delegate = self;
    }
    return _loginVC;
}

- (XOWMZFController *)zhifuvc
{
    if (!_zhifuvc)
    {
        _zhifuvc = [[XOWMZFController alloc]init];
        _zhifuvc.delegate = self;
    }
    return _zhifuvc;
}
- (NSMutableData *)recevieData
{
    if (!_recevieData)
    {
        _recevieData = [[NSMutableData alloc] init];
    }
    return _recevieData;
}

- (NSString *)currentVersion
{
    if ([[NSBundle mainBundle].infoDictionary valueForKey:@"currentversion"])
        return [[NSBundle mainBundle].infoDictionary valueForKey:@"currentversion"];
    else
        return @"1.1.9";
}
- (void)actionForUserCenter
{
    _helper = helperManager().getPara();
    if ([_helper.accountID length] > 0 && [_helper.token length] > 0)
    {
        if (![NSStringFromClass([[UIViewController currentVC] class]) isEqualToString:@"XOWMUserViewController"])
        {
            XOWMUserViewController *userVC = [[XOWMUserViewController alloc] init];
            userVC.delegate = self;
            userVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [[UIViewController currentVC] presentViewController:userVC animated:YES completion:nil];
        }
    }
    else
    {
        _prepareLogin();
    }
}
- (void)getIP:(NSNotification *)notify
{
    _helper = helperManager().getPara();
    _registerPlatform(_helper.appID, _helper.serviceHeader, _helper.publicKey);
}
static void setupCallBack()
{
    if (!_YJDPlatform.delegate && _para.callback)
    {
        _para.callback(_YJDPlatform.receiveDict);
    }
    else if (_YJDPlatform.delegate && [_YJDPlatform.delegate respondsToSelector:@selector(receiveCallBack:)])
    {
        [_YJDPlatform.delegate receiveCallBack:_YJDPlatform.receiveDict];
    }
}
#pragma mark - SKLLoginViewControllerDelegate---Method
- (void)yjd_didreceiveDictYJDLoginViewController:(NSDictionary *)dict
{
    _helper = helperManager().getPara();
    self.receiveDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    _helper.accountID = [self.receiveDict valueForKey:@"accountid"];
    _helper.token = [self.receiveDict valueForKey:@"accesstoken"];
    helperManager().setPara(_helper);
    if (VERSION_2_0_0_LATER)
    {
        if ([[dict valueForKey:@"bindstate"] intValue] == 0)
        {
            //            [XOWMPlatform yjd_authenticate];//弹出认证窗口
        }
        else
        {
            setupCallBack();
        }
    }
    else
    {
        setupCallBack();
    }
}

#pragma mark - SKLRZViewControllerDelegate---Method
- (void)yjd_actionForAuthenticate
{
    if (VERSION_2_0_0_LATER)
    {
        if ([[self.receiveDict valueForKey:@"phone"] length] < 1)
        {
            //             [NSClassFromString(@"SKLBindViewController") yjd_show];
        }
    }
    setupCallBack();
}

#pragma mark - YJDZFControllerDelegate
- (void)yjd_didReceiveFromYJDZFController:(XOWMProductPara )product
{
    if (_YJDPlatform.delegate && [_YJDPlatform.delegate respondsToSelector:@selector(receiveCallBack:)])
    {
        [_YJDPlatform.delegate receiveCallBack:nil];
    }
}

#pragma mark - YJDUserViewControllerDelegate
- (void)yjd_YJDUserViewControllerDelegate
{
    _prepareLogin();
}

#pragma mark - NSURLSessionDelegate method
//接受到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //__FUNCTION__ c语言字符串用s
    DeLog(@"1。 %s",__FUNCTION__);
    //允许服务器回传数据
    completionHandler(NSURLSessionResponseAllow);
}

//接受服务器回传的数据可能执行多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [_YJDPlatform.recevieData appendData:data];
}

//请求成功或者失败
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error
{
    if (error && (error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            _YJDPlatform.statusCode = 202;
            _YJDPlatform.info = [NSString stringWithFormat:@"%@",error.localizedDescription];
        });
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *newError;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_YJDPlatform.recevieData options:NSJSONReadingMutableLeaves error:&newError];
        if (newError)
        {
            _YJDPlatform.recevieData = nil;
            NSLog(@"initSDK error === %@",[newError localizedDescription]);
        }
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess =  [transdata yjd_verifySign:sign];
        if (isSuccess)
        {
            NSDictionary *transDict =  [transdata yjd_rc4_dec: helperManager().getPara().appID];
            _YJDPlatform.info = [transDict valueForKey:@"info"];
            int  code = [[transDict valueForKey:@"code"] intValue];
            
            if (code == 100)
            {
                _YJDPlatform.statusCode = 200;
                _helper = helperManager().getPara();
                _helper.yx = [transDict valueForKey:@"gameurl"];
                _helper.state = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"checkstate"]];
                helperManager().setPara(_helper);
                _YJDPlatform.userBtn.hidden = ([[transDict valueForKey:@"floatstate"] intValue] == 0)?YES:NO;
                DeLog(@"初始化成功");
            }
            else
            {
                _YJDPlatform.statusCode = code;
            }
        }
        else
        {
            _YJDPlatform.info = @"网络不给力或已断开，请检查网络";
            _YJDPlatform.statusCode = 204;
        }
        _YJDPlatform.recevieData = nil;
    });
    [session finishTasksAndInvalidate];
}
@end
